<template>
  <div class="system-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-title">⚙️ 系统设置</div>
    </div>

    <!-- 九宫格功能入口 -->
    <div class="function-grid">
      <div 
        v-for="(item, index) in functionItems" 
        :key="index" 
        class="grid-item"
        @click="openFunctionModal(item)"
        :class="{ disabled: item.disabled }"
      >
        <div class="grid-icon">{{ item.icon }}</div>
        <div class="grid-label">{{ item.label }}</div>
        <div v-if="item.badge" class="grid-badge">{{ item.badge }}</div>
      </div>
    </div>

    <!-- 进度条展示区域 - 两排横向布局 -->
    <div class="progress-section">
      <!-- 经验修炼模块 -->
      <div class="cultivation-row">
        <div class="row-header">
          <div class="row-title">📊 经验修炼</div>
        </div>
        <div class="progress-grid">
          <div 
            v-for="(item, index) in expCultivation" 
            :key="index"
            class="progress-card"
            :style="{ animationDelay: index * 0.05 + 's' }"
          >
            <div class="card-name">{{ item.name }}</div>
            <div class="progress-bar-container">
              <div 
                class="progress-bar" 
                :style="{ width: item.percent + '%' }"
                :class="'progress-' + item.type"
              >
                <span class="progress-text">{{ item.percent.toFixed(0) }}%</span>
              </div>
            </div>
            <div class="card-value">{{ item.current }}/{{ item.max }}</div>
            <button 
              class="upgrade-btn"
              @click="upgradeExpCultivation(index)"
              :disabled="!item.canUpgrade || upgradingExp[index]"
            >
              {{ upgradingExp[index] ? '升级中' : '升级' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 内功修炼模块 -->
      <div class="cultivation-row">
        <div class="row-header">
          <div class="row-title">⚡ 内功修炼</div>
        </div>
        <div class="progress-grid">
          <div 
            v-for="(item, index) in internalCultivation" 
            :key="index"
            class="progress-card"
            :style="{ animationDelay: (index + 4) * 0.05 + 's' }"
          >
            <div class="card-name">{{ item.name }}</div>
            <div class="progress-bar-container">
              <div 
                class="progress-bar" 
                :style="{ width: item.percent + '%' }"
                :class="'progress-' + item.type"
              >
                <span class="progress-text">{{ item.percent.toFixed(0) }}%</span>
              </div>
            </div>
            <div class="card-value">{{ item.current }}/{{ item.max }}</div>
            <button 
              class="upgrade-btn"
              @click="upgradeInternalCultivation(index)"
              :disabled="!item.canUpgrade || upgradingInternal[index]"
            >
              {{ upgradingInternal[index] ? '升级中' : '升级' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能弹框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <div class="modal-title">{{ currentModal?.label }}</div>
          <div class="modal-close" @click="closeModal">×</div>
        </div>
        <div class="modal-body">
          <component :is="currentModal?.component" v-if="currentModal?.component" />
          <div v-else class="modal-placeholder">
            <text>{{ currentModal?.label }}功能正在开发中...</text>
          </div>
        </div>
      </div>
    </div>

    <!-- 全局底部导航栏 -->
    <CustomTabBar />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import api from '@/api'
import EmailModal from './components/EmailModal.vue'
import FriendModal from './components/FriendModal.vue'

export default {
  components: {
    EmailModal,
    FriendModal
  },
  data() {
    return {
      // 九宫格功能项
      functionItems: [
        { key: 'email', label: '邮件', icon: '📧', component: 'EmailModal', badge: null },
        { key: 'friend', label: '好友', icon: '👥', component: 'FriendModal', badge: null },
        { key: 'settings', label: '设置', icon: '⚙️', disabled: false },
        { key: 'notice', label: '公告', icon: '📢', disabled: false },
        { key: 'cdk', label: '兑换码', icon: '🎫', disabled: false },
        { key: 'help', label: '帮助', icon: '❓', disabled: false },
        { key: 'feedback', label: '反馈', icon: '💬', disabled: false },
        { key: 'about', label: '关于', icon: 'ℹ️', disabled: false },
        { key: 'empty', label: '', icon: '', disabled: true }
      ],
      showModal: false,
      currentModal: null,
      // 经验修炼数据
      expCultivation: [
        { name: '基础经验', current: 0, max: 1000, percent: 0, type: 'exp1', canUpgrade: false },
        { name: '进阶经验', current: 0, max: 2000, percent: 0, type: 'exp2', canUpgrade: false },
        { name: '高级经验', current: 0, max: 5000, percent: 0, type: 'exp3', canUpgrade: false },
        { name: '顶级经验', current: 0, max: 10000, percent: 0, type: 'exp4', canUpgrade: false }
      ],
      upgradingExp: [false, false, false, false],
      // 内功修炼数据
      internalCultivation: [
        { name: '基础内功', current: 0, max: 1000, percent: 0, type: 'internal1', canUpgrade: false },
        { name: '进阶内功', current: 0, max: 2000, percent: 0, type: 'internal2', canUpgrade: false },
        { name: '高级内功', current: 0, max: 5000, percent: 0, type: 'internal3', canUpgrade: false },
        { name: '顶级内功', current: 0, max: 10000, percent: 0, type: 'internal4', canUpgrade: false }
      ],
      upgradingInternal: [false, false, false, false],
      // 定时器
      updateTimer: null
    }
  },
  computed: {
    ...mapGetters('user', {
      userNickname: 'nickname',
      userLevel: 'level',
      realmName: 'realmName'
    }),
    ...mapGetters('sect', {
      sectInfo: 'sectInfo'
    }),
    sectName() {
      return this.sectInfo?.sectName || '无门无派'
    }
  },
  mounted() {
    this.loadData()
    this.startAutoUpdate()
  },
  beforeDestroy() {
    this.stopAutoUpdate()
  },
  methods: {
    // 打开功能弹框
    openFunctionModal(item) {
      if (item.disabled || !item.key || item.key === 'empty') return
      
      this.currentModal = item
      this.showModal = true
      
      // 如果是邮件或好友，加载数据
      if (item.key === 'email') {
        this.loadEmailData()
      } else if (item.key === 'friend') {
        this.loadFriendData()
      }
    },
    
    // 关闭弹框
    closeModal() {
      this.showModal = false
      this.currentModal = null
    },
    
    // 加载初始数据
    async loadData() {
      await Promise.all([
        this.loadExpCultivation(),
        this.loadInternalCultivation(),
        this.updateFunctionBadges()
      ])
    },
    
    // 加载经验修炼数据
    async loadExpCultivation() {
      try {
        // TODO: 根据实际后端接口调整
        const response = await api.post('/system/cultivation/exp', {})
        if (response && response.code === 1 && response.data) {
          const data = response.data
          if (Array.isArray(data)) {
            data.forEach((item, index) => {
              if (this.expCultivation[index]) {
                this.$set(this.expCultivation[index], 'current', item.current || 0)
                this.$set(this.expCultivation[index], 'max', item.max || 1000)
                this.$set(this.expCultivation[index], 'percent', Math.min(100, ((item.current || 0) / (item.max || 1)) * 100))
                this.$set(this.expCultivation[index], 'canUpgrade', item.canUpgrade || false)
              }
            })
          }
        }
      } catch (error) {
        console.error('加载经验修炼数据失败:', error)
      }
    },
    
    // 加载内功修炼数据
    async loadInternalCultivation() {
      try {
        // TODO: 根据实际后端接口调整
        const response = await api.post('/system/cultivation/internal', {})
        if (response && response.code === 1 && response.data) {
          const data = response.data
          if (Array.isArray(data)) {
            data.forEach((item, index) => {
              if (this.internalCultivation[index]) {
                this.$set(this.internalCultivation[index], 'current', item.current || 0)
                this.$set(this.internalCultivation[index], 'max', item.max || 1000)
                this.$set(this.internalCultivation[index], 'percent', Math.min(100, ((item.current || 0) / (item.max || 1)) * 100))
                this.$set(this.internalCultivation[index], 'canUpgrade', item.canUpgrade || false)
              }
            })
          }
        }
      } catch (error) {
        console.error('加载内功修炼数据失败:', error)
      }
    },
    
    // 升级经验修炼
    async upgradeExpCultivation(index) {
      if (this.upgradingExp[index] || !this.expCultivation[index].canUpgrade) return
      
      this.$set(this.upgradingExp, index, true)
      try {
        const response = await api.post('/system/cultivation/exp_upgrade', { index })
        if (response && response.code === 1) {
          uni.showToast({ title: '升级成功', icon: 'success' })
          await this.loadExpCultivation()
        } else {
          uni.showToast({ title: response?.msg || '升级失败', icon: 'none' })
        }
      } catch (error) {
        console.error('升级经验修炼失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.$set(this.upgradingExp, index, false)
      }
    },
    
    // 升级内功修炼
    async upgradeInternalCultivation(index) {
      if (this.upgradingInternal[index] || !this.internalCultivation[index].canUpgrade) return
      
      this.$set(this.upgradingInternal, index, true)
      try {
        const response = await api.post('/system/cultivation/internal_upgrade', { index })
        if (response && response.code === 1) {
          uni.showToast({ title: '升级成功', icon: 'success' })
          await this.loadInternalCultivation()
        } else {
          uni.showToast({ title: response?.msg || '升级失败', icon: 'none' })
        }
      } catch (error) {
        console.error('升级内功修炼失败:', error)
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.$set(this.upgradingInternal, index, false)
      }
    },
    
    // 更新功能入口徽章（如未读邮件数）
    async updateFunctionBadges() {
      try {
        // 获取邮件未读数
        const emailResponse = await api.post('/email/info', {})
        if (emailResponse && emailResponse.code === 1 && Array.isArray(emailResponse.data)) {
          const unreadCount = emailResponse.data.filter(email => email.read === 0).length
          const emailItem = this.functionItems.find(item => item.key === 'email')
          if (emailItem && unreadCount > 0) {
            this.$set(emailItem, 'badge', unreadCount > 99 ? '99+' : String(unreadCount))
          }
        }
      } catch (error) {
        console.error('更新功能徽章失败:', error)
      }
    },
    
    // 加载邮件数据（用于邮件弹框）
    async loadEmailData() {
      // EmailModal 组件内部会加载数据
    },
    
    // 加载好友数据（用于好友弹框）
    async loadFriendData() {
      // FriendModal 组件内部会加载数据
    },
    
    // 开始自动更新
    startAutoUpdate() {
      this.stopAutoUpdate()
      this.updateTimer = setInterval(() => {
        this.loadExpCultivation()
        this.loadInternalCultivation()
      }, 10000) // 每10秒更新一次
    },
    
    // 停止自动更新
    stopAutoUpdate() {
      if (this.updateTimer) {
        clearInterval(this.updateTimer)
        this.updateTimer = null
      }
    }
  }
}
</script>

<style scoped>
/* 页面容器 - 武侠风格 */
.system-page {
  min-height: 100vh;
  max-height: 100vh;
  overflow: hidden;
  background: linear-gradient(180deg, #e8dcc4 0%, #d4c4a8 100%);
  display: flex;
  flex-direction: column;
  padding: 0 0 70px 0;
  font-family: "STSong", "Noto Serif SC", serif;
}

/* 页面标题 */
.page-header {
  padding: 15px 15px 10px;
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  border-bottom: 3px solid #4b3a2a;
  box-shadow: 0 4px 12px rgba(139, 111, 71, 0.3);
  flex-shrink: 0;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  letter-spacing: 2px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  text-align: center;
}

/* 九宫格布局 */
.function-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 12px 12px 10px;
  flex-shrink: 0;
}

.grid-item {
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid #c4a57b;
  border-radius: 12px;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 3px 10px rgba(139, 111, 71, 0.2);
  position: relative;
}

.grid-item:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(139, 111, 71, 0.3);
  border-color: #8b6f47;
}

.grid-item.disabled {
  opacity: 0.4;
  cursor: not-allowed;
  background: rgba(200, 200, 200, 0.5);
}

.grid-icon {
  font-size: 28px;
  margin-bottom: 6px;
}

.grid-label {
  font-size: 12px;
  color: #4a3c2a;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.grid-badge {
  position: absolute;
  top: 6px;
  right: 6px;
  background: linear-gradient(135deg, #ff4757 0%, #d63031 100%);
  color: white;
  font-size: 10px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
  box-shadow: 0 2px 6px rgba(255, 71, 87, 0.4);
}

/* 进度条展示区域 - 两排布局 */
.progress-section {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px 15px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.cultivation-row {
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid #c4a57b;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 3px 10px rgba(139, 111, 71, 0.2);
}

.row-header {
  padding-bottom: 8px;
  border-bottom: 2px solid #d8c7a3;
  margin-bottom: 10px;
}

.row-title {
  font-size: 16px;
  font-weight: bold;
  color: #4a3c2a;
  letter-spacing: 1px;
}

/* 进度卡片 - 2列网格布局 */
.progress-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.progress-card {
  background: rgba(248, 246, 241, 0.6);
  border: 1px solid #d8c7a3;
  border-radius: 10px;
  padding: 10px;
  opacity: 0;
  animation: fadeInUp 0.5s ease forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card-name {
  font-size: 12px;
  color: #6b4f3b;
  font-weight: 600;
  margin-bottom: 6px;
  text-align: center;
}

.progress-bar-container {
  width: 100%;
  height: 18px;
  background: rgba(139, 111, 71, 0.15);
  border-radius: 9px;
  overflow: hidden;
  margin-bottom: 6px;
  position: relative;
  border: 1px solid #d8c7a3;
}

.progress-bar {
  height: 100%;
  border-radius: 9px;
  transition: width 0.5s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.progress-text {
  position: absolute;
  font-size: 10px;
  font-weight: bold;
  color: #fff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  z-index: 1;
}

.progress-exp1 { background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%); }
.progress-exp2 { background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%); }
.progress-exp3 { background: linear-gradient(90deg, #722ed1 0%, #9254de 100%); }
.progress-exp4 { background: linear-gradient(90deg, #fa8c16 0%, #ffa940 100%); }

.progress-internal1 { background: linear-gradient(90deg, #f5222d 0%, #ff4d4f 100%); }
.progress-internal2 { background: linear-gradient(90deg, #eb2f96 0%, #f759ab 100%); }
.progress-internal3 { background: linear-gradient(90deg, #13c2c2 0%, #36cfc9 100%); }
.progress-internal4 { background: linear-gradient(90deg, #faad14 0%, #ffc53d 100%); }

.card-value {
  font-size: 10px;
  color: #8b6f47;
  text-align: center;
  margin-bottom: 6px;
}

.upgrade-btn {
  width: 100%;
  padding: 6px 12px;
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  color: white;
  border: 2px solid #4b3a2a;
  border-radius: 8px;
  font-size: 11px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.upgrade-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(75, 58, 42, 0.3);
}

.upgrade-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #d0d0d0;
  border-color: #999;
  color: #666;
}

/* 弹框样式 - 武侠风格 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(75, 58, 42, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-content {
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  background: rgba(248, 246, 241, 0.98);
  border: 3px solid #8b6f47;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(139, 111, 71, 0.5);
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  background: linear-gradient(135deg, #8b6f47 0%, #6b4f3b 100%);
  color: white;
  border-bottom: 3px solid #4b3a2a;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  letter-spacing: 1px;
}

.modal-close {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 24px;
  transition: all 0.3s ease;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.modal-close:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
  background: rgba(255, 255, 255, 0.5);
}

.modal-placeholder {
  text-align: center;
  padding: 40px 20px;
  color: #6b4f3b;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .page-header {
    padding: 12px 12px 8px;
  }
  
  .header-title {
    font-size: 18px;
  }
  
  .function-grid {
    padding: 10px 10px 8px;
    gap: 8px;
  }
  
  .grid-item {
    padding: 10px;
  }
  
  .grid-icon {
    font-size: 24px;
  }
  
  .grid-label {
    font-size: 11px;
  }
  
  .progress-section {
    padding: 0 10px 12px;
    gap: 10px;
  }
  
  .cultivation-row {
    padding: 10px;
  }
  
  .row-title {
    font-size: 15px;
  }
  
  .progress-grid {
    gap: 8px;
  }
  
  .progress-card {
    padding: 8px;
  }
  
  .card-name {
    font-size: 11px;
  }
  
  .progress-bar-container {
    height: 16px;
  }
  
  .upgrade-btn {
    font-size: 10px;
    padding: 5px 10px;
  }
}
</style>
